import { Input, Select, Switch, Table, Tooltip, TreeSelect, message } from 'antd';
import Cls from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import { connect } from 'umi';
import pageStyles from '@/common/pageLayout.less';
import { getLevelZeroJson, getLoadMapList, getSelectDataMapList, getTenantID, tooltipLength, getUserID } from '@/utils';
import { getUserDataList } from '@/components/SchemaComponent/SchemaManage/hooks';
import { ILoadMapTypeAll } from '@/common';
import { manualUpServices, positionList, editDetailServices } from '../services/UpdataService';
import { DictionaryRenderFun } from '../../Acommon';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { readReadShowFileService } from '@/services/BaseLayout';
import { getBaseUrl } from '@/services/urlconst';

const DifferTable = ({
  curRes,
  inventoryID,
  onSaveDiffFun,
  isDetail,
  detailInfo,
  Detaildata,
  taskPushPagination,
  taskPushLoading,
  editDetailRun,
  editDetailLoading,
}) => {
  const styleFixCls = 'contract-styfixcls-';

  const [dataSource, setDataSource] = useState<any>([]);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //资产来源
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //资产品牌
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
  ]);

  /** 资产类型 */
  const brandList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`], 'name', 'id', true);
  /** 资产存放区域类型 */
  const locationList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`], 'name', 'id', true);

  const { positionRun, positiondata } = positionList();

  /** 手动变更当前项 */
  const [changeObj, setChangeObj] = useState<any>({});
  /** 手动变更当前项状态 */
  const [changeState, setChangeState] = useState<any>('');

  /** 手动变更接口回调 */
  const manualUpCallback = (res: any) => {
    if (res && res.msgFlag) {
      let arr = JSON.parse(JSON.stringify(dataSource));
      let idx = arr.findIndex((item: any) => {
        return item.id === changeObj.id;
      });
      if (idx !== -1) {
        arr[idx].changeState = changeState;
      }
      setDataSource(arr);
      onEditTable(changeObj, 'changeState', changeState);
      message.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  };

  /** 轻阅读预览 */
  const { readReadShowFileRun, readReadShowFileLoading } = readReadShowFileService();

  /** 手动变更接口 */
  const { manualUpRun, manualUpLoading } = manualUpServices(manualUpCallback);

  /** 获取用户接口 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList();

  useEffect(() => {
    setDataSource(Detaildata?.rows || []);
    getUserRun({ userDepartmentID: '' });
  }, [Detaildata]);

  useEffect(() => {
    onSaveDiffFun(dataSource);
  }, [dataSource]);

  const onEditTableRow = (record, type, val) => {
    editDetailRun({
      ...record,
      [type]: val,
    });
  };

  const onEditTable = (record, type, val) => {
    if (type === 'location' || type === 'changeLocation') {
      editDetailRun({
        ...record,
        [type]: val,
      });
    } else {
      const newData = [...dataSource];
      const index = newData.findIndex((item) => record.id === item.id);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          [type]: val,
        });
      }
      onSaveDiffFun(newData);
    }
  };

  const onEditTableSelect = (record, type, option) => {
    if (type === 'changeUserID') {
      editDetailRun({
        ...record,
        [type]: option?.id,
        changeUserName: option?.realName,
      });
    } else {
      editDetailRun({
        ...record,
        [type]: option?.id,
        userName: option?.realName,
      });
    }
    // const newData = [...dataSource];
    // const index = newData.findIndex((item) => record.id === item.id);
    // if (index > -1) {
    //   const item = newData[index];
    //   if (type === 'changeUserID') {
    //     newData.splice(index, 1, {
    //       ...item,
    //       [type]: option?.id,
    //       changeUserName: option?.realName,
    //     });
    //   }
    // }
    // onSaveDiffFun(newData);
  };

  const columns: any = [
    {
      title: '资产编号',
      dataIndex: 'assetCode',
      key: 'assetCode',
      visible: true,
      width: 160,
      fixed: 'left',
      unDrag: false,
      render: (text: string | null, record: Record<string, any>) => {
        return (
          <Tooltip title={text} placement="top">
            <span className={pageStyles['over-flow-hidden']} style={{ maxWidth: '100%' }} id={record?.id}>
              {text ? text : '--'}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '资产名称',
      dataIndex: 'assetName',
      key: 'assetName',
      visible: true,
      width: 160,
      unDrag: false,
      render: (text: string | null, record: Record<string, any>) => {
        return (
          <Tooltip title={text} placement="top">
            <span className={pageStyles['over-flow-hidden']} style={{ maxWidth: '100%' }} id={record?.id}>
              {text ? text : '--'}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '资产分类',
      dataIndex: 'assetTypeName',
      key: 'assetTypeName',
      visible: true,
      width: 150,
      unDrag: false,
      render: (text: string | null, record: Record<string, any>) => DictionaryRenderFun({ text, isState: false }),
    },
    {
      title: '盘点结果',
      dataIndex: 'changeState',
      key: 'changeState',
      visible: true,
      width: 150,
      unDrag: false,
      render: (text: string | null, record: Record<string, any>) => {
        return (
          <Tooltip title={text} placement="top">
            <span className={pageStyles['over-flow-hidden']} style={{ maxWidth: '100%' }} id={record?.id}>
              {text === '0' && '盘点发生变更'}
              {text === '2' && '盘点发生变更自动变更完成'}
              {text === '3' && '未盘点'}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '品牌',
      dataIndex: 'brandType',
      key: 'brandType',
      visible: true,
      width: 150,
      unDrag: false,
      render: (text: string | null, record: Record<string, any>) => {
        return (
          <Tooltip title={text} placement="top">
            <span className={pageStyles['over-flow-hidden']} style={{ maxWidth: '100%' }} id={record?.id}>
              {text ? text : '--'}
            </span>
          </Tooltip>
        );
      },
    },
    {
      title: '盘点前',
      children: [
        {
          title: '规格型号',
          dataIndex: 'paramsInfo',
          key: 'paramsInfo',
          visible: true,
          width: 150,
          unDrag: false,
          render: (value: number | any, record: Record<string, any>, index: number) => {
            if (isDetail) {
              return value ? value : '--';
            } else {
              return (
                <Input
                  defaultValue={value}
                  style={{ width: '100%' }}
                  onChange={(e) => {
                    onEditTable(record, 'paramsInfo', e?.target?.value);
                  }}
                  onBlur={(e) => {
                    onEditTableRow(record, 'paramsInfo', e?.target?.value);
                  }}
                />
              );
            }
          },
        },
        {
          title: '使用人',
          dataIndex: 'userID',
          key: 'userID',
          visible: true,
          width: 150,
          unDrag: false,
          render: (value: number | any, record: Record<string, any>, index: number) => {
            if (isDetail) {
              return value ? record?.userName : '--';
            } else {
              return (
                <Select
                  fieldNames={{
                    label: 'realName',
                    value: 'id',
                  }}
                  style={{
                    width: '100%',
                  }}
                  defaultValue={record?.userID}
                  onChange={(val, option) => {
                    onEditTableSelect(record, 'userID', option);
                  }}
                  onFocus={() => {
                    getUserRun({ userDepartmentID: record?.changeUseDepartmentID });
                  }}
                  options={getUserList}
                />
              );
            }
          },
        },
        {
          title: '存放区域',
          dataIndex: 'location',
          key: 'location',
          visible: true,
          width: 150,
          unDrag: false,
          render: (value: number | any, record: Record<string, any>, index: number) => {
            if (isDetail) {
              return value ? record?.locationName?.split('||')[0] : '--';
            } else {
              return (
                <TreeSelect
                  loading={mapLoading}
                  placeholder="请选择"
                  treeData={locationList}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }}
                  value={value}
                  style={{ width: '100%' }}
                  showSearch={true}
                  treeNodeFilterProp={'name'}
                  allowClear={true}
                  onChange={(val) => {
                    onEditTable(record, 'location', val);
                  }}
                />
              );
            }
          },
        },
        // {
        //   title: '详细地点',
        //   dataIndex: 'remark',
        //   key: 'remark',
        //   visible: true,
        //   width: 150,
        //   unDrag: false,
        //   render: (value: number | any, record: Record<string, any>, index: number) => {
        //     if (isDetail) {
        //       return value ? value : '--';
        //     } else {
        //       return (
        //         <Input.TextArea
        //           value={value}
        //           rows={1}
        //           cols={1}
        //           placeholder="请输入"
        //           onChange={(e) => {
        //             onEditTable(record, 'remark', e.target.value);
        //           }}
        //         />
        //       );
        //     }
        //   },
        // },
      ],
    },
    {
      title: '盘点后',
      children: [
        // {
        //   title: '品牌',
        //   dataIndex: 'brandType',
        //   key: 'brandType',
        //   visible: true,
        //   width: 150,
        //   unDrag: false,
        //   render: (value: number | any, record: Record<string, any>) => {
        //     if (isDetail) {
        //       return value ? value : '--';
        //     } else {
        //       return (
        //         <Input
        //           style={{
        //             width: '100%',
        //           }}
        //           defaultValue={value}
        //           placeholder={'请输入'}
        //           onChange={(e) => {
        //             onEditTable(record, 'brandType', e?.target?.value);
        //           }}
        //           onBlur={(e) => {
        //             onEditTableRow(record, 'brandType', e?.target?.value);
        //           }}
        //         />
        //       );
        //     }
        //   },
        // },
        {
          title: '规格型号',
          dataIndex: 'changeBrandParam',
          key: 'changeBrandParam',
          visible: true,
          width: 150,
          unDrag: false,
          render: (value: number | any, record: Record<string, any>, index: number) => {
            if (isDetail) {
              return value ? value : '--';
            } else {
              return (
                <Input
                  defaultValue={value}
                  style={{ width: '100%' }}
                  onChange={(e) => {
                    onEditTable(record, 'changeBrandParam', e?.target?.value);
                  }}
                  onBlur={(e) => {
                    onEditTableRow(record, 'changeBrandParam', e?.target?.value);
                  }}
                />
              );
            }
          },
        },
        {
          title: '使用人',
          dataIndex: 'changeUserID',
          key: 'changeUserID',
          visible: true,
          width: 150,
          unDrag: false,
          render: (value: number | any, record: Record<string, any>, index: number) => {
            if (isDetail) {
              return value ? record?.changeUserName : '--';
            } else {
              return (
                <Select
                  fieldNames={{
                    label: 'realName',
                    value: 'id',
                  }}
                  style={{
                    width: '100%',
                  }}
                  defaultValue={record?.changeUserName}
                  onChange={(val, option) => {
                    onEditTableSelect(record, 'changeUserID', option);
                  }}
                  onFocus={() => {
                    getUserRun({ userDepartmentID: record?.changeUseDepartmentID });
                  }}
                  options={getUserList}
                />
              );
            }
          },
        },
        {
          title: '存放区域',
          dataIndex: 'changeLocation',
          key: 'changeLocation',
          visible: true,
          width: 150,
          unDrag: false,
          render: (value: number | any, record: Record<string, any>, index: number) => {
            if (isDetail) {
              return value ? record?.changeLocationName?.split('||')[0] : '--';
            } else {
              return (
                <TreeSelect
                  loading={mapLoading}
                  placeholder="请选择"
                  treeData={locationList}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }}
                  value={value}
                  style={{ width: '100%' }}
                  showSearch={true}
                  treeNodeFilterProp={'name'}
                  allowClear={true}
                  onChange={(val) => {
                    onEditTable(record, 'changeLocation', val);
                  }}
                />
              );
            }
          },
        },
        // {
        //   title: '详细地点',
        //   dataIndex: 'remark',
        //   key: 'remark',
        //   visible: true,
        //   width: 150,
        //   unDrag: false,
        //   render: (value: number | any, record: Record<string, any>, index: number) => {
        //     if (isDetail) {
        //       return value ? value : '--';
        //     } else {
        //       return (
        //         <Input.TextArea
        //           value={value}
        //           rows={1}
        //           cols={1}
        //           placeholder="请输入"
        //           onChange={(e) => {
        //             onEditTable(record, 'remark', e.target.value);
        //           }}
        //         />
        //       );
        //     }
        //   },
        // },
      ],
    },
    {
      title: '图片',
      dataIndex: 'inventoryURL',
      key: 'inventoryURL',
      visible: true,
      width: 67,
      unDrag: false,
      render: (value: number | any, record: Record<string, any>, index: number) => {
        return (
          <>
            <div className={pageStyles['over-flow-hidden']}>
              {value && value?.split(',')[0] && (
                <Tooltip title={tooltipLength(value.split(',')[0], 50)} placement="top">
                  <img
                    style={{ width: '50px', height: '50px' }}
                    src={getBaseUrl() + value.split(',')[0]}
                    onClick={() => {
                      readReadShowFileRun({ fieldPath: `${getBaseUrl()}${value.split(',')[0]}` });
                    }}
                  />
                  {/* <a
                  >
                    {value.split(',')[0]}
                  </a> */}
                </Tooltip>
              )}
            </div>
          </>
        );
      },
    },
    {
      title: '条码图片',
      dataIndex: 'inventoryURL',
      key: 'inventoryURL',
      visible: true,
      width: 67,
      unDrag: false,
      render: (value: number | any, record: Record<string, any>, index: number) => {
        return (
          <>
            <div className={pageStyles['over-flow-hidden']}>
              {value && value?.split(',')[1] && (
                <Tooltip title={tooltipLength(value.split(',')[1], 50)} placement="top">
                  <img
                    style={{ width: '50px', height: '50px' }}
                    src={getBaseUrl() + value.split(',')[1]}
                    onClick={() => {
                      readReadShowFileRun({ fieldPath: `${getBaseUrl()}${value.split(',')[1]}` });
                    }}
                  />
                  {/* <a
                  >
                    {value.split(',')[1]}
                  </a> */}
                </Tooltip>
              )}
            </div>
          </>
        );
      },
    },
    {
      title: '是否更新信息',
      dataIndex: 'inventoryType',
      key: 'inventoryType',
      visible: false,
      fixed: 'right',
      width:
        detailInfo?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006` &&
        detailInfo?.paramObject['100199031019']?.mactivitiTaskList[0]?.assigneeID === getUserID()
          ? 150
          : 0,
      render: (text: string | number | null, record: Record<string, any>, index: number) => {
        return (
          <div style={{ color: '100%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            <Switch
              checkedChildren="是"
              unCheckedChildren="否"
              // disabled={isDetail}
              checked={text === 0 ? false : true}
              onChange={(checked) => {
                setChangeObj(record);
                setChangeState(!checked ? 0 : 1);
                onEditTable(record, 'inventoryType', !checked ? 0 : 1);
                editDetailRun({ ...record, inventoryType: !checked ? 0 : 1 });
              }}
            />
          </div>
        );
      },
    },
  ];

  return (
    <div className={Cls('list-table', `${styleFixCls}updateStepsBox-tableBox`, 'ExtractModalTable')}>
      <Table
        size="small"
        bordered
        scroll={{ x: 1200, y: 'true' }}
        columns={columns}
        dataSource={dataSource}
        rowKey={'id'}
        loading={taskPushLoading || editDetailLoading}
        pagination={{
          ...taskPushPagination,
          showTotal: () => {
            return '共' + Detaildata?.total + '条';
          },
        }}
      />
    </div>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(DifferTable);
